package com.compass.doctor.ui.patient

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnNumberChangeCallBack
import com.compass.doctor.databinding.ActivityMassMessagingBinding
import com.compass.doctor.ui.patient.adapter.MassPatientAdapter
import com.compass.doctor.ui.patient.viewmodel.ExamineViewModel
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.TIME_YEAR
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.PatientInfo
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.DateUtils
import com.compass.framework.utils.FullyGridLayoutManager
import com.compass.framework.utils.MoneyInputFilter
import com.compass.framework.utils.getColorFromResource
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog

/**
 * Description： 群发消息
 * Date:2024/1/31 17:16
 */
class MassMessagingActivity : BaseVBActivity<ActivityMassMessagingBinding>() {


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, MassMessagingActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val examineViewModel: ExamineViewModel by viewModels()


    private var patient: PatientInfo? = null//接收传递过来的数据

    private val maxSelectNum = 10
    private var mPatients: ArrayList<PatientInfo> = ArrayList()
    private lateinit var mAdapter: MassPatientAdapter
    private var giveIsOpen: Boolean = false//默认关闭
    private var giveFlag: Int = 0 //默认关闭
    //患者选择回调
    private val mActivityResultLauncherPatient: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    patient = intent.serializable("patient")
                    patient?.let { patientInfo ->
                        if (!isAdd(patientInfo)){
                            mAdapter.addItem(patientInfo)
                            mBinding.tvPatientNumber.text="(${mAdapter.data.size}/10)"
                        }else {
                            showToast("该患者已经添加")
                        }
                    }
                }
            }
        }

    private var sendingTime: Long = -1//发送时间
    override fun initView(savedInstanceState: Bundle?) {
        mAdapter = MassPatientAdapter(this, mPatients)
        mAdapter.selectMax = maxSelectNum
        mBinding.rcyJoin.apply {
            layoutManager = FullyGridLayoutManager(
                this@MassMessagingActivity,
                5, GridLayoutManager.VERTICAL, false
            )
            adapter = mAdapter
        }


        mBinding.edtNumber.addTextChangedListener {
            if (it.toString().isEmpty()) mBinding.edtNumber.textSize =
                14f else mBinding.edtNumber.textSize = 18f
        }


        mBinding.tvGiveTime.addTextChangedListener {
            if (it.toString().isEmpty())  mBinding.tvGiveTime.textSize= 14f else mBinding.tvGiveTime.textSize=18f
        }
        setIsGive(giveIsOpen)
        showGift()
    }


    private fun isAdd(patient:PatientInfo):Boolean{
        for (item in mAdapter.data){
            if (item.id==patient.id){
                return true
            }
        }
        return false


    }

    /**
     * 显示赠送按钮
     */
   private fun showGift() {
        val appHospitalConfig=   UserInfoManager.getUserInfo()?.appHospitalConfigRespVO
        appHospitalConfig?.let {
            if (it.isAllowGive == "1") mBinding.conLayoutGift.visible() else  mBinding.conLayoutGift.gone()

            val filter = MoneyInputFilter()
            filter.setMaxValue(it.giveRow.toDouble())
            filter.setDecimalLength(0)
            mBinding.edtNumber.filters = arrayOf(filter)

            val filterTime = MoneyInputFilter()
            filterTime.setMaxValue(it.giveTime.toDouble())
            filterTime.setDecimalLength(0)
            mBinding.tvGiveTime.filters = arrayOf(filterTime)

            mBinding.edtNumber.setHint("请输入赠送条数(最多${it.giveRow}条)")
            mBinding.tvGiveTime.setHint("请输入赠送有效时长(${it.giveTime}小时内)")

        }?:kotlin.run {
            mBinding.conLayoutGift.gone()
        }
    }

    override fun intListener() {

        mBinding.tvRemark.addTextChangedListener {
            if (it.toString().isEmpty()){
                mBinding.tvTagExplain.text = "0/200"
            }  else{
                mBinding.tvTagExplain.text = "${it?.length}/200"
            }
        }

        mAdapter.setOnItemClickListener(object : MassPatientAdapter.OnItemClickListener {
            override fun openPatientList() {
                val intent = Intent(this@MassMessagingActivity, PatientListActivity::class.java)
                intent.putExtra(KEY_CONSULT_TYPE, 1)
                mActivityResultLauncherPatient?.launch(intent)
            }

            override fun onItemClick(v: View?, position: Int) {
//                val list:ArrayList<String> = ArrayList()
//                for (item in mAdapter.data){
//                    list.add(item.id)
//                }
//                LogUtil.e("lits==${list.toJson()}")
            }
        })
        mAdapter.setOnNumberChange( object :OnNumberChangeCallBack{
            override fun numberChangeCallBack(number: Int) {
                mBinding.tvPatientNumber.text="(${number}/10)"
            }
        })
        mBinding.giveSc.onClick {
            giveIsOpen = !giveIsOpen
            setIsGive(giveIsOpen)
        }
        mBinding.tvSendTime.onClick {
            showDataDialog()
        }

        mBinding.tvConfirm.onClick {
            if (mAdapter.data.isEmpty()){
                 showToast("请先选择患者")
                 return@onClick
             }
            if (sendingTime<0){
                showToast("请先选择发送时间")
                return@onClick
            }
            val message= mBinding.tvRemark.text.toString().trim()
            if (message.isEmpty()){
                showToast("请先输入群发内容")
                return@onClick
            }
            val giveNumber= mBinding.edtNumber.text.toString().trim()
            val giveTime= mBinding.tvGiveTime.text.toString().trim()
            if (giveIsOpen){

                if (giveNumber.isEmpty()||giveNumber.toInt()==0){
                    showToast("请先输入赠送条数")
                    return@onClick
                }

                if (giveTime.isEmpty()||giveTime.toInt()==0){
                    showToast("请先输入有效时长")
                    return@onClick
                }

            }

            val list:ArrayList<String> = ArrayList()
              for (item in mAdapter.data){
                  list.add(item.id)
              }

            examineViewModel.massMessaging(sendingTime,list,message,giveFlag,giveNumber,giveTime)
        }

    }


    override fun initData() {
        examineViewModel.massLiveData.observe(this){
            if (it){
                showToast("发送成功")
                finish()
            }
        }
    }

    //设置是否赠送免费消息
    private fun setIsGive(isOpen: Boolean) {
        mBinding.giveSc.isChecked = isOpen
        if (isOpen) giveFlag=1 else giveFlag=0
        mBinding.viewLine.visibility = if (isOpen) View.VISIBLE else View.GONE
        mBinding.llGiveNumber.visibility = if (isOpen) View.VISIBLE else View.GONE
        mBinding.llGiveTime.visibility = if (isOpen) View.VISIBLE else View.GONE

    }

    /**
     * 设置会诊时间
     */
    private fun showDataDialog() {
        CardDatePickerDialog.builder(this)
            .setTitle("开始时间")
            .showBackNow(false)
            .setMinTime(System.currentTimeMillis())
            .setMaxTime(System.currentTimeMillis()+TIME_YEAR)
            .setLabelText("年", "月", "日", "时", "分")
            .setBackGroundModel(CardDatePickerDialog.STACK)
            .setDisplayType(
                DateTimeConfig.YEAR,
                DateTimeConfig.MONTH,
                DateTimeConfig.DAY,
                DateTimeConfig.HOUR,
                DateTimeConfig.MIN
            )
            .setThemeColor(getColorFromResource(R.color.color_0165b8))
            .setOnChoose { milliecond ->
                sendingTime = milliecond
                mBinding.tvSendTime.text=DateUtils.conversionTime(sendingTime,DateUtils.FORMAT_TWO)
            }.build().show()
    }
}